package com.peanutplan.blog.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.peanutplan.blog.constant.ServerConfig;
import com.peanutplan.blog.utils.FileUploadUtils;

@Controller
public class CommonController {

//	 private static final Logger log = LoggerFactory.getLogger(CommonController.class);

	@Value("${default_upload_basedir}")
    private String default_upload_basedir;
	
	/**
	 * 文件上传路径
	 */
	public static final String UPLOAD_PATH = "/profile/upload/";

	@Autowired
	private ServerConfig serverConfig;

	@RequestMapping("/ueditor/config")
	public String config(String action,HttpServletRequest request,HttpServletResponse response) {
        System.out.println(action);
        if("config".equals(action)) {
        	return "redirect:/admin/plugins/ueditor/jsp/config.json";
        }else {
        	return "forward:/common/upload";
        }
    }

	/**
	 * 通用上传请求
	 */
	@PostMapping("/common/upload")
	@ResponseBody
	public Map<String, Object> uploadFile(MultipartFile upfile) throws Exception {
		Map<String, Object> map = new HashMap<>(3);
		try {
			// 上传文件路径
			String filePath = default_upload_basedir;
			// 上传并返回新文件名称
			String fileName = FileUploadUtils.upload(filePath, upfile);
			String url = UPLOAD_PATH + fileName;
			map.put("url", url);
            map.put("state", "SUCCESS");
            map.put("original", "");
		} catch (Exception e) {
			map.put("url", "");
            map.put("state", "SUCCESS");
            map.put("original", "");
		}
		
		return map;
	}

	public String setFileDownloadHeader(HttpServletRequest request, String fileName)
			throws UnsupportedEncodingException {
		final String agent = request.getHeader("USER-AGENT");
		String filename = fileName;
		if (agent.contains("MSIE")) {
			// IE浏览器
			filename = URLEncoder.encode(filename, "utf-8");
			filename = filename.replace("+", " ");
		} else if (agent.contains("Firefox")) {
			// 火狐浏览器
			filename = new String(fileName.getBytes(), "ISO8859-1");
		} else if (agent.contains("Chrome")) {
			// google浏览器
			filename = URLEncoder.encode(filename, "utf-8");
		} else {
			// 其它浏览器
			filename = URLEncoder.encode(filename, "utf-8");
		}
		return filename;
	}
}
